package com.sip.stream.utils.zfy.yuv;

import android.util.SparseArray;

import com.gosuncn.zfyluancher.ZFYLauncherJNI;

import java.util.Stack;

public class YUVToolFactory {
    public static final String TAG = "YUVToolFactory";
    private static SparseArray<Stack<byte[]>> yuvDateDataSource = new SparseArray<>();
    public static YUVToolDataSource dataSource = new YUVToolDataSource() {
        @Override
        public byte[] obtainOutputData(int i) {
            return YUVToolFactory.obtainOutputData(i);
        }

        @Override
        public void release() {
            YUVToolFactory.yuvDateDataSource.clear();
        }

        @Override
        public void recycle(byte[] bArr) {
            YUVToolFactory.recycleData(bArr);
        }
    };

    public static synchronized byte[] obtainOutputData(int i) {
        byte[] pop;
        synchronized (YUVToolFactory.class) {
            try {
                pop = yuvDateDataSource.get(i).pop();
            } catch (Exception unused) {
                return new byte[i];
            }
        }
        return pop;
    }

    public static synchronized void recycleData(byte[] bArr) {
        synchronized (YUVToolFactory.class) {
            if (yuvDateDataSource.get(bArr.length) == null) {
                Stack<byte[]> stack = new Stack<>();
                stack.add(bArr);
                yuvDateDataSource.put(bArr.length, stack);
            } else {
                yuvDateDataSource.get(bArr.length).push(bArr);
            }
        }
    }

    public static synchronized byte[] copyNV12ToNV21(byte[] bArr, int width, int height) {
        synchronized (YUVToolFactory.class) {
            byte[] obtainOutputData = obtainOutputData(bArr.length);
            if (ZFYLauncherJNI.NV12ToNV21(bArr, obtainOutputData, width, height) == 0) {
                return obtainOutputData;
            }
            return null;
        }
    }
}
